//
//  QAddressBookVC.m
//  QoilPublic
//
//  Created by 杨凯 on 2017/8/8.
//  Copyright © 2017年 杨凯. All rights reserved.
//

#import "QAddressBookVC.h"
#import "QContactModel.h"
#import "QAddressBookCell.h"
#import <AddressBook/AddressBook.h>

@interface QAddressBookVC ()<UISearchControllerDelegate,UISearchResultsUpdating>


@property (nonatomic, strong) UISearchController *searchController;

@property(nonatomic,strong)NSMutableArray *searArr;

@property(nonatomic,strong)NSMutableArray *dataArray;

@property(nonatomic,strong)NSMutableArray *sectionArray;

@property(nonatomic,strong)NSMutableArray *titleArray;

@property(nonatomic,assign)BOOL isRegist;

@end

@implementation QAddressBookVC

- (NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)sectionArray{
    if(!_sectionArray){
        _sectionArray = [NSMutableArray array];
    }
    return _sectionArray;
}

- (NSMutableArray *)titleArray{
    if(!_titleArray){
        _titleArray = [NSMutableArray array];
    }
    return _titleArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.title = @"通讯录";
    _searArr = [NSMutableArray array];

    [QViewUtility setupNavigationBarBackForController:self backSelector:@selector(bac)];
    
    
    
    [self loadPerson];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"QAddressBookCell" bundle:nil] forCellReuseIdentifier:@"QAddressBookCell"];

    [self createSearchBar];
    

    NSString *weekday = [self calculateWeek:[NSDate date]];
    

    if ([weekday isEqualToString:@"周五"]) {
        [self requestData];
    }
}


- (void)bac{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    if(_isRegist){
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];//设置状态栏
    }else{
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];//设置状态栏
    }
}

- (void)createSearchBar{
    
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchController.delegate = self;
    _searchController.searchResultsUpdater = self;
    _searchController.dimsBackgroundDuringPresentation = NO;
    UISearchBar *bar = self.searchController.searchBar;
    bar.barStyle = UIBarStyleDefault;
    UIImageView *view = [[[bar.subviews objectAtIndex:0] subviews] firstObject];
    view.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;
    view.layer.borderWidth = 1;
    bar.translucent = YES;
    bar.barTintColor = [UIColor groupTableViewBackgroundColor];
    bar.tintColor = [QColorUtility defaultMainColor];
    CGRect rect = bar.frame;
    rect.size.height = 44;
    bar.frame = rect;
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    [backView addSubview:bar];
    bar.frame = CGRectMake(0, 0, kScreenWidth, 44);
    bar.centerX = backView.centerX;
    self.tableView.tableHeaderView = backView;
    self.searchController.definesPresentationContext = YES;
}

#pragma mark - UISearchBarDelegate

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    
    NSString *searchString = [self.searchController.searchBar text];
    
    if (_searArr!= nil) {
        [_searArr removeAllObjects];
    }
    for (QContactModel * model in _dataArray) {
        if ([model.name containsString:searchString] || [model.phone containsString:searchString]) {
            [self.searArr addObject:model];
        }
    }
    
    //刷新表格
    [self.tableView reloadData];
}

- (void)willPresentSearchController:(UISearchController *)searchController{
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];//设置状态栏
    _isRegist = YES;
}

- (void)willDismissSearchController:(UISearchController *)searchController{
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];//设置状态栏
    _isRegist = NO;
}

- (void)loadPerson
{
    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
    
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error){
            
            CFErrorRef *error1 = NULL;
            ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
            [self copyAddressBook:addressBook];
        });
    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
        
        CFErrorRef *error = NULL;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
        [self copyAddressBook:addressBook];
    }
    else {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            UILabel *lab = [QViewUtility createLabelWithFrame:CGRectMake(0, 0, kScreenWidth - 50, 50) font:15 textAlignment:1 textColor:[QColorUtility defaultBackColor] text:@"请在iPhone的“设置-隐私-通讯录”选项中，允许油到了访问你的通讯录"];
            lab.numberOfLines = 0;
            lab.centerX = self.view.centerX;
            lab.centerY = self.view.centerY - 60;
            [self.view addSubview:lab];
            
        
            

        });
    }
}

- (void)copyAddressBook:(ABAddressBookRef)addressBook
{
    CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
    CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
    
    for ( int i = 0; i < numberOfPeople; i++){
        ABRecordRef person = CFArrayGetValueAtIndex(people, i);
        QContactModel *model = [[QContactModel alloc] init];
        NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
        if (firstName == nil) {
            firstName = @"";
        }
        
        if (lastName == nil) {
            lastName = @"";
        }
        model.name = [NSString stringWithFormat:@"%@%@",lastName,firstName];
        
        //读取电话多值
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
//            NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
            //获取該Label下的电话值
            NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
            if (k==0) {
                model.phone = personPhone;

            }
            
        }
        
        //读取照片
        NSData *image = (__bridge NSData*)ABPersonCopyImageData(person);
        model.imgStr = image;
        [self.dataArray addObject:model];
        
    }
    
    [self setupSection];
}

- (void)setupSection{
    
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    
    NSUInteger numberOfSections = [[collation sectionTitles] count];
    NSMutableArray *newSectionArray =  [[NSMutableArray alloc]init];
    for (NSUInteger index = 0; index<numberOfSections; index++) {
        [newSectionArray addObject:[[NSMutableArray alloc]init]];
    }
    
    for (QContactModel *model in self.dataArray) {
        NSUInteger sectionIndex = [collation sectionForObject:model collationStringSelector:@selector(name)];
        [newSectionArray[sectionIndex] addObject:model];
    }
    
    for (NSUInteger index=0; index<numberOfSections; index++) {//已经按首字母排序好的数组
        NSMutableArray *personsForSection = newSectionArray[index];
        NSArray *sortedPersonsForSection = [collation sortedArrayFromArray:personsForSection collationStringSelector:@selector(name)];
        newSectionArray[index] = sortedPersonsForSection;
    }
    
    
    NSMutableArray *temp = [NSMutableArray new];
    [newSectionArray enumerateObjectsUsingBlock:^(NSArray *arr, NSUInteger idx, BOOL *stop) {
        if (arr.count == 0) {
            [temp addObject:arr];
        } else {
            [self.titleArray addObject:[collation sectionTitles][idx]];
        }
    }];
    
    [newSectionArray removeObjectsInArray:temp];
    
    self.sectionArray = newSectionArray;
    
}

#pragma mark --- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if(self.searchController.active){
        return 1;
    }else{
        return self.sectionArray.count;
    }

    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if(self.searchController.active){
        return _searArr.count;
    }else{
        return [self.sectionArray[section] count];
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    QAddressBookCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QAddressBookCell" forIndexPath:indexPath];
    
    if(self.searchController.active){
        cell.model = _searArr[indexPath.row];
    }else{
        cell.model = self.sectionArray[indexPath.section][indexPath.row];;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 55;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if(section == self.sectionArray.count){
        return 30;
    }else{
        return 0.01;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    if(section == self.sectionArray.count){
        UIView *new = [UIView new];
        new.backgroundColor = [UIColor groupTableViewBackgroundColor];
        return new;
    }else{
        return [UIView new];
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc]init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.searchController.active) {
        return 0.00;
    }else{
        return 30;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (self.searchController.active) {
        return nil;
    }else{
        return [self.titleArray objectAtIndex:section];
    }
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    tableView.sectionIndexColor = [UIColor grayColor];
    if (self.searchController.active) {
        return nil;
    }else{
        return self.titleArray;

    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    if (self.AddressBookBlock) {
        
        QContactModel *model =[[QContactModel alloc] init];

        if(self.searchController.active){
            model = _searArr[indexPath.row];
        }else{
            model = self.sectionArray[indexPath.section][indexPath.row];;
        }

        if ([model.phone containsString:@"-"]) {
            model.phone = [model.phone stringByReplacingOccurrencesOfString:@"-" withString:@""];
        }
        
        if ([model.phone containsString:@"+86"]) {
            model.phone = [model.phone stringByReplacingOccurrencesOfString:@"+86" withString:@""];
        }
        
        self.AddressBookBlock(model.phone,model.name);
    }
    
    [self.searchController setActive:NO];
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)requestData{
    
    NSString *url = [QParamService urlWithAction:@"uab/save"];

    NSString *str =@"";
    NSString *str1=@"";
    for (QContactModel *model in _dataArray) {
        if (model.phone == nil) {
            model.phone = @"";
        }
        if (model.name == nil) {
            model.name = @"";
        }
        
        if ([str1 isEqualToString:@""]) {
            str1 = [NSString stringWithFormat:@"%@=%@",model.name,model.phone];
        }else{
            str = [NSString stringWithFormat:@"%@=%@",model.name,model.phone];
            str1 = [NSString stringWithFormat:@"%@,%@",str1,str];
        }
    }

    NSDictionary *param = [QParamService saveAddressBookWithInfo:str1];
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user setValue:[NSDate date] forKey:@"updateAddressBook"];

            CLog(@"===上传成功");
        }else{
            CLog(@"===上传失败");

        }
    }];
    
}

- (NSString *)calculateWeek:(NSDate *)date{
    //计算week数
    NSCalendar * myCalendar = [NSCalendar currentCalendar];
    myCalendar.timeZone = [NSTimeZone systemTimeZone];
    NSInteger week = [[myCalendar components:NSCalendarUnitWeekday fromDate:date] weekday];
    
    NSLog(@"week : %zd",week);
    switch (week) {
        case 1:
        {
            return @"周日";
        }
        case 2:
        {
            return @"周一";
        }
        case 3:
        {
            return @"周二";
        }
        case 4:
        {
            return @"周三";
        }
        case 5:
        {
            return @"周四";
        }
        case 6:
        {
            return @"周五";
        }
        case 7:
        {
            return @"周六";
        }
    }
    
    return @"";
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
